<template>
  <div class="duanxing">
    <el-form :rules="rules" :model="form" label-width="80px" ref="form">
      <el-form-item>
        <h1>手机号登陆</h1>
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input v-model.number="form.mobile">请输入手机号</el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="form.code">
          <el-button slot="append" :disabled="disabled" @click="huoqu">{{
            tips
          }}</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dluFN">登陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { postyanzheng, postdxdenglu } from "@/api";
export default {
  data() {
    const checkphone = (rule, value, callback) => {
      if (/^1\d{10}$/g.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };

    const checkyanzheng = (rule, value, callback) => {
      if (/^\d{4}$/g.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的验证码"));
      }
    };

    return {
      disabled: false,
      t: null,
      tips: "验证码",
      form: {
        mobile: "",
        code: ""
      },
      rules: {
        mobile: [
          { validator: checkphone, trigger: "blur" } /* validator:自动化校验 */
        ],
        code: [{ validator: checkyanzheng, trigger: "blur" }]
      }
    };
  },
  methods: {
    //点击获取验证码
    huoqu() {
      // 判断
      if (!/^1\d{10}$/g.test(this.form.mobile)) {
        this.$message.error("请输正确的手机号");
        return;
      }
      this.t = setInterval(() => {
        if (this.tips == "验证码") {
          //发送异步请求
          postyanzheng(this.form.mobile).then(res => {
            // console.log(res);
            if (res.meta.state == 201) {
              this.$message.success(res.meta.msg);
            } else {
              this.$message.error(res.meta.msg);
            }
          });
          this.tips = 10;
          this.disabled = true;
        } else {
          this.tips--;
        }
        if (this.tips == 0) {
          clearInterval(this.t);
          this.tips = "验证码";
          this.disabled = false;
        }
      }, 1000);
    },

    //点击登录按钮
    dluFN() {
      this.$refs.form.validate(isSuccess => {
        if (isSuccess) {
          //发送异步请求
          postdxdenglu(this.form).then(res => {
            console.log(res);
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.duanxing {
  width: 100%;
  height: 100%;
  background-color: grey;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-form {
    width: 300px;
    height: 260px;
    text-align: center;
    .el-form-item {
      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
